const pluginName = 'TxtToJs'
const { readFileSync } = require('fs')
const { RawSource } = require('webpack-sources');

module.exports = class TxtToJs {
    constructor({ template, filename }) {
        if (!template) {
            throw new Error('"template" must be configured')
        }
        this.template = template
        this.filename = filename || 'newjsByTxt.js'
    }
    apply(compiler) {
        compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
            compilation.hooks.processAssets.tap({
                name: pluginName,
                stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE, // 选择适当的阶段
                additionalAssets: true,
            }, () => {
                //webpack5新的修改资源方式
                const _sourceContent = readFileSync(this.template, 'utf-8')
                compilation.emitAsset(this.filename, new RawSource(_sourceContent));
            });

        })
    }
}